package com.tungse.netty2.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.TimeUnit;

/**
 * @Author : Tungse
 * @Date: 2025/7/5 10:15
 * @Description:
 */
public class NettyClient2 {

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap()
            .group(new NioEventLoopGroup())
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline()
                            .addLast(new LineBasedFrameDecoder(1024))
                            .addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            .addLast(new SimpleChannelInboundHandler<String>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                            System.out.println(msg);
                        }
                    });
                }
            });
        ChannelFuture channelFuture = bootstrap.connect("localhost", 8080);

        channelFuture.addListener(f->{
            if (f.isSuccess()){
                System.out.println("连接成功");
                EventLoop eventExecutors = channelFuture.channel().eventLoop();
                eventExecutors.scheduleAtFixedRate(()->{
                    channelFuture.channel().writeAndFlush("nihao"+System.currentTimeMillis()+"\n");
                },0,1, TimeUnit.SECONDS);
            }else {
                System.out.println("连接失败");
            }
        });
    }
}
